package com.hugh.commom.netty.client;

import com.hugh.commom.netty.client.codec.ClientFrameDecoder;
import com.hugh.commom.netty.client.codec.ClientFrameEncoder;
import com.hugh.commom.netty.client.codec.ClientProtocolDecoder;
import com.hugh.commom.netty.client.codec.ClientProtocolEncoder;
import com.hugh.commom.netty.client.handle.ClientIdleCheckHandler;
import com.hugh.commom.netty.client.handle.diapatcher.RequestPendingCenter;
import com.hugh.commom.netty.client.handle.diapatcher.ResponseDispatcherHandler;
import io.netty.bootstrap.Bootstrap;
import io.netty.channel.ChannelFuture;
import io.netty.channel.ChannelInitializer;
import io.netty.channel.ChannelOption;
import io.netty.channel.ChannelPipeline;
import io.netty.channel.EventLoopGroup;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.SocketChannel;
import io.netty.channel.socket.nio.NioSocketChannel;
import io.netty.handler.logging.LogLevel;
import io.netty.handler.logging.LoggingHandler;
import lombok.extern.slf4j.Slf4j;

/**
 * @Author: Hugh
 * @Date: 2020/6/13
 */
@Slf4j
public class NettyClientOpen {

    public Bootstrap doOpen() throws Exception{

        RequestPendingCenter requestPendingCenter = new RequestPendingCenter();

        //1) 初始化UserClientHandler
        //2)创建连接池对象
        EventLoopGroup group = new NioEventLoopGroup();
        //3)创建客户端的引导对象
        Bootstrap bootstrap =  new Bootstrap();

        LoggingHandler loggingHandler = new LoggingHandler(LogLevel.INFO);

        //4)配置启动引导对象
        bootstrap.group(group)
                //设置通道为NIO
                .channel(NioSocketChannel.class)
                //设置请求协议为TCP
                .option(ChannelOption.TCP_NODELAY,true)
                //监听channel 并初始化
                .handler(new ChannelInitializer<SocketChannel>() {
                    @Override
                    protected void initChannel(SocketChannel socketChannel) throws Exception {
                        //获取ChannelPipeline
                        ChannelPipeline pipeline = socketChannel.pipeline();
                        pipeline.addLast("idleHandler", new ClientIdleCheckHandler());
                        pipeline.addLast(loggingHandler);
                        //设置编码
                        pipeline.addLast(new ClientFrameDecoder());
                        pipeline.addLast(new ClientFrameEncoder());

                        pipeline.addLast(new ClientProtocolEncoder());
                        pipeline.addLast(new ClientProtocolDecoder());
                        pipeline.addLast(new ResponseDispatcherHandler(requestPendingCenter));

                    }
                });

        return bootstrap;
        //5)连接服务端
//        return bootstrap.connect(ip, port).sync();

    }
}
